package com.ftw.commons.utils

import android.annotation.SuppressLint
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import com.ftw.commons.BaseApplication
import com.ftw.commons.SharedPreferenceUtils
import com.ftw.commons.log.LogUtils
import java.io.File
import java.io.FileNotFoundException
import java.text.SimpleDateFormat
import java.util.*


/**
 * 描    述：
 * 作    者：fantianwen
 * 时    间：2020/2/27
 */

object FileUtils {


    /**
     * 获取SDCard的目录路径功能
     */
    // 获取下载目录
    val sdCardPath: String
        get() {
            var sdcardDir: File? = null
            val sdcardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
            if (sdcardExist) {
                sdcardDir =
                    File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .toString() + "/midu邮箱/"
                    )
                if (!sdcardDir.isDirectory) {
                    sdcardDir.mkdir()
                }

            }
            return sdcardDir!!.toString()
        }

    /**
     * sdCard临时文件
     */
    val sdCardTmp: String
        get() {
            var sdcardDir: File? = null
            val sdcardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
            if (sdcardExist) {
                sdcardDir =
                    File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .toString() + "/temp/"
                    )
                if (!sdcardDir.isDirectory) {
                    sdcardDir.mkdir()
                }

            }
            return sdcardDir!!.toString()
        }


    /**
     * 保存图片到相册
     */
    @SuppressLint("ObsoleteSdkInt")
    fun saveImgToAlubm(filePath: String) {
        val file = File(filePath)
        try {

            MediaStore.Images.Media.insertImage(
                BaseApplication.instance.contentResolver,
                file.absolutePath, file.name, null
            )
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }
        // 通知图库更新
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(
                BaseApplication.instance,
                arrayOf<String>(file.absolutePath),
                null
            ) { _, uri ->
                val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                mediaScanIntent.data = uri
                BaseApplication.instance.sendBroadcast(mediaScanIntent)
            }
        } else {
            val relationDir: String = file.getParent()
            val file1 = File(relationDir)
            BaseApplication.instance.sendBroadcast(
                Intent(
                    Intent.ACTION_MEDIA_MOUNTED,
                    Uri.fromFile(file1.absoluteFile)
                )
            )
        }
    }


    //移除文件，获取文件时间与当前时间对比，我这时间定位5天，删除五天前的文件
    @SuppressLint("SimpleDateFormat")
    fun removeFileByTime(dirPath: String, date: Int) { //获取目录下所有文件
        val allFile = getDirAllFile(File(dirPath))
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm")
        //获取当前时间
        var end = Date(System.currentTimeMillis())
        try {
            end = dateFormat.parse(dateFormat.format(Date(System.currentTimeMillis())))
        } catch (e: Exception) {
            LogUtils.d("dataformat exeption e $e")
        }
        LogUtils.d("getNeedRemoveFile  dirPath = $dirPath")

        for (file in allFile) { //ComDef
            try { //文件时间减去当前时间
                val start: Date = dateFormat.parse(dateFormat.format(Date(file.lastModified())))
                val diff = end.time - start.time //这样得到的差值是微秒级别
                val days = diff / (1000 * 60 * 60 * 24)
                if (date <= days) {
                    deleteFile(file)
                }
            } catch (e: Exception) {
                LogUtils.d("dataformat exeption e $e")
            }
        }
    }

    //获取指定目录下一级文件
    fun getDirAllFile(file: File): List<File> {
        val fileList: MutableList<File> = ArrayList()
        val fileArray: Array<File> = file.listFiles() ?: return fileList
        for (f in fileArray) {
            fileList.add(f)
        }
        fileSortByTime(fileList)
        return fileList
    }

    //对文件进行时间排序
    fun fileSortByTime(fileList: List<File>) {
        Collections.sort(fileList) { p1, p2 ->
            if (p1.lastModified() < p2.lastModified()) {
                -1
            } else 1
        }
    }

    //删除文件夹及文件夹下所有文件
    fun deleteFile(file: File) {
        if (file.isDirectory) {
            file.listFiles()?.let {
                it.forEach {
                    deleteFile(it)
                }
            }
        }
    }

    fun isDelete(createDate: String?, daysNum: Int): Boolean {
        when (TextUtils.isEmpty(createDate)) {
            true -> {
                return false
            }
            else -> {
                val end = Date(System.currentTimeMillis())
                val simpleDate = SimpleDateFormat(
                    "yyyy-mm-dd hh:mm:ss",
                    Locale.CHINA
                )
                val start: Date = simpleDate.parse(createDate)
                val diff = end.time - start.time //这样得到的差值是微秒级别
                val days = diff / (1000 * 60 * 60 * 24)
                return daysNum > days
            }

        }


    }


}